//
//  ViewController.m
//  socket请求百度
//
//  Created by Sizhu Ba on 2017/8/31.
//  Copyright © 2017年 Sizhu Ba. All rights reserved.
//

#import "ViewController.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIWebView *web;
@property (nonatomic, assign) int clientSocket; //socket的描述符
@end

@implementation ViewController
- (IBAction)btt:(id)sender {
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //1 连接百度的服务器
    BOOL result = [self connect:@"192.168.2.112" port:1227];
    if (!result){
        NSLog(@"%@",@"连接失败");
        return ;
    }
    NSLog(@"%@",@"连接成功");
    //构造请求头
    NSString *request = @"GET / HTTP/1.1\r\n" //回车换行 /r/n
    "Host: www.baidu.com\r\n"
//    "User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36\r\n"
//    "Cookie: BAIDUID=9CFE944CCD1989E7FF7FFE80813940EC:FG=1; BIDUPSID=9CFE944CCD1989E7FF7FFE80813940EC; PSTM=1503818834; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; bd_traffictrace=010859; plus_lsv=8b4f19c2305ae69a; plus_cv=1::m:21732389; H_WISE_SIDS=102569_114551_117615_118010_115654_103569_117467_114244_119025_119005_118942_118894_118866_118852_118835_118801_107918_118156_118674_107320_118450_118145_118971_118235_116725_117582_117335_117233_117432_118121_118327_118325_118132_118219_115538_118473_118965_118102_117558_117635_116408_118750_110085; Hm_lvt_12423ecbc0e2ca965d84259063d35238=1504227558; Hm_lpvt_12423ecbc0e2ca965d84259063d35238=1504227558; BD_HOME=0; H_PS_PSSID=1428_21113_17001_20718; BD_UPN=1a3253\r\n"
    "Connection: close\r\n\r\n";
    
    
    
    
    NSString * response = [self sendAndRecv:request]; //服务器返回的响应
    NSLog(@"拿到的响应%@",response);
    //当拿到响应要关闭连接
    close(self.clientSocket);
    //找到\r\n\r\n的范围
   // NSRange range =  [response rangeOfString:@"\r\n\r\n"];
    //从 \r\n\r\n之后的第一个位置开始截取
    //截取y响应 \r\n
  //  NSString * html =   [response substringFromIndex:range.length+range.location];
    NSLog(@"获取到的数据%@",response);
  //  [self.web loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.baidu.com"]];
}



//1 连接服务器
- (BOOL)connect:(NSString *)ip port:(int)port{
    
    //2 连接服务器
    
    //第一个参数 socket的描述符
    
    //第二个参数 结构体 IP地址和短裤
    
    //第三个参数  结构体的长度 sizeof
    
    //返回值 成功0 失败非0
    int clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    self.clientSocket = clientSocket;
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip.UTF8String);
    addr.sin_port = htons(port);
    
    int result = connect(clientSocket, (const struct sockaddr *) &addr, sizeof(addr));
    if (result == 0) {
        return YES;
    }else{
        return NO;
    }
    
    
    
    
}
//2 发送和接收数据
- (NSString *)sendAndRecv:(NSString *)sendMsg {
    //3 向服务发送数据
    
    //const void *发送的数据
    
    //size_t 发送数据的大小 (字符个数)
    
    //int 是阻塞 一般是0
    
    const char *msg = sendMsg.UTF8String;
    ssize_t sendCount = send(self.clientSocket, msg, strlen(msg), 0); //成功则返回实际传送出去的字符数，失败返回－1
    NSLog(@"发送的字节数 %zd",sendCount);
    
    //4 接收服务器返回的数据
    //返回的是实际接受的字节个数
    //第一个参数int socket的描述符
    //第二个参数 void * 就是返回的数据存放的位置
    //第四个参数 int是否阻塞 0
    
    uint8_t buffer[1024];
    
    NSMutableData *mData = [NSMutableData data];
    
    ssize_t recvCount = recv(self.clientSocket, buffer, sizeof(buffer), 0);//返回的是实际接收的字节个数
    [mData appendBytes:buffer length:recvCount];
    
    //服务器会返回多次数据，等所有的数据都接收完成，再转换成字符串
    while (recvCount != 0) {
        recvCount = recv(self.clientSocket, buffer, sizeof(buffer), 0);
        NSLog(@"接收的字节数 %zd",recvCount);
        [mData appendBytes:buffer length:recvCount];
        
    }
    
    //把字节数组转换成字符串
    NSString *recvMsg = [[NSString alloc] initWithData:mData.copy encoding:NSUTF8StringEncoding];
    return recvMsg;
}
@end
